/**
 * 文本更新安全包装器
 * 解决微信小程序 "updateTextView:fail 32776 not found" 错误
 */

class TextUpdateSafeWrapper {
  constructor() {
    this.componentStates = new Map()
    this.updateQueue = new Map()
    this.isProcessing = false
  }

  /**
   * 注册组件
   * @param {Object} component - Vue组件实例
   */
  registerComponent(component) {
    if (!component || !component.$options) return

    const componentId = this.getComponentId(component)
    this.componentStates.set(componentId, {
      component,
      isActive: true,
      isMounted: true,
      lastUpdateTime: Date.now()
    })

    // 监听组件销毁
    const originalBeforeDestroy = component.$options.beforeDestroy || []
    const destroyHandlers = Array.isArray(originalBeforeDestroy) 
      ? originalBeforeDestroy 
      : [originalBeforeDestroy]

    component.$options.beforeDestroy = [
      ...destroyHandlers,
      () => this.unregisterComponent(component)
    ]
  }

  /**
   * 注销组件
   * @param {Object} component - Vue组件实例
   */
  unregisterComponent(component) {
    const componentId = this.getComponentId(component)
    const state = this.componentStates.get(componentId)
    
    if (state) {
      state.isActive = false
      state.isMounted = false
      
      // 清理待处理的更新
      this.updateQueue.delete(componentId)
      
      // 延迟删除状态，避免正在进行的更新出错
      setTimeout(() => {
        this.componentStates.delete(componentId)
      }, 1000)
    }
  }

  /**
   * 安全更新组件数据
   * @param {Object} component - Vue组件实例
   * @param {Object} data - 要更新的数据
   * @param {Function} callback - 更新完成回调
   */
  safeUpdate(component, data, callback) {
    if (!this.validateComponent(component)) {
      console.warn('组件已销毁，跳过更新:', data)
      return Promise.resolve()
    }

    return new Promise((resolve, reject) => {
      try {
        // 微信小程序环境
        if (typeof component.setData === 'function') {
          this.safeSetData(component, data, () => {
            if (callback) callback()
            resolve()
          })
        }
        // Vue环境
        else {
          this.safeVueUpdate(component, data)
          if (callback) callback()
          resolve()
        }
      } catch (error) {
        console.error('文本更新失败:', error)
        this.handleUpdateError(component, error, data)
        reject(error)
      }
    })
  }

  /**
   * 安全的微信小程序 setData
   * @param {Object} component - 小程序页面/组件实例
   * @param {Object} data - 数据
   * @param {Function} callback - 回调
   */
  safeSetData(component, data, callback) {
    if (!component || typeof component.setData !== 'function') {
      console.warn('无效的小程序组件实例')
      return
    }

    // 验证数据
    const validData = this.validateUpdateData(data)
    if (!validData || Object.keys(validData).length === 0) {
      console.warn('无效的更新数据:', data)
      if (callback) callback()
      return
    }

    try {
      component.setData(validData, () => {
        if (this.validateComponent(component)) {
          if (callback) callback()
        }
      })
    } catch (error) {
      console.error('setData 执行失败:', error)
      throw error
    }
  }

  /**
   * 安全的Vue数据更新
   * @param {Object} component - Vue组件实例
   * @param {Object} data - 数据
   */
  safeVueUpdate(component, data) {
    if (!component || !component.$data) {
      console.warn('无效的Vue组件实例')
      return
    }

    // 使用 nextTick 确保在下一个DOM更新周期执行
    component.$nextTick(() => {
      if (this.validateComponent(component)) {
        Object.keys(data).forEach(key => {
          try {
            // 直接赋值，Vue会自动处理响应式更新
            component[key] = data[key]
          } catch (error) {
            console.error(`更新属性 ${key} 失败:`, error)
          }
        })
      }
    })
  }

  /**
   * 延迟更新（等待DOM准备）
   * @param {Object} component - 组件实例
   * @param {Object} data - 数据
   * @param {number} delay - 延迟时间（毫秒）
   */
  deferredUpdate(component, data, delay = 50) {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (this.validateComponent(component)) {
          this.safeUpdate(component, data).then(resolve).catch(resolve)
        } else {
          resolve()
        }
      }, delay)
    })
  }

  /**
   * 批量更新
   * @param {Object} component - 组件实例
   * @param {Array} updates - 更新数组 [{data, delay}]
   */
  async batchUpdate(component, updates) {
    if (!this.validateComponent(component)) return

    for (const update of updates) {
      if (!this.validateComponent(component)) break
      
      if (update.delay) {
        await this.deferredUpdate(component, update.data, update.delay)
      } else {
        await this.safeUpdate(component, update.data)
      }
    }
  }

  /**
   * 验证组件状态
   * @param {Object} component - 组件实例
   * @returns {boolean}
   */
  validateComponent(component) {
    if (!component) return false

    // 简化验证逻辑，减少复杂性
    try {
      // Vue组件验证
      if (component.$data !== undefined) {
        return !component._isDestroyed && !component._isBeingDestroyed && component._isComponentActive !== false
      }
      // 微信小程序组件验证
      if (typeof component.setData === 'function') {
        return component.data !== undefined
      }
      return false
    } catch (error) {
      console.warn('组件验证失败:', error)
      return false
    }
  }

  /**
   * 验证更新数据
   * @param {Object} data - 要验证的数据
   * @returns {Object} 验证后的数据
   */
  validateUpdateData(data) {
    if (!data || typeof data !== 'object') return {}

    const validData = {}
    Object.keys(data).forEach(key => {
      const value = data[key]
      
      // 跳过 undefined 值
      if (value !== undefined) {
        // 确保字符串值不为 null
        if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
          validData[key] = value
        } else if (value === null) {
          validData[key] = ''
        } else if (typeof value === 'object') {
          validData[key] = value
        }
      }
    })

    return validData
  }

  /**
   * 处理更新错误
   * @param {Object} component - 组件实例
   * @param {Error} error - 错误对象
   * @param {Object} data - 尝试更新的数据
   */
  handleUpdateError(component, error, data) {
    const componentId = this.getComponentId(component)
    
    console.error('文本更新错误详情:', {
      componentId,
      error: error.message,
      data,
      timestamp: new Date().toISOString()
    })

    // 如果是 32776 错误，标记组件为不活跃
    if (error.message && error.message.includes('32776')) {
      const state = this.componentStates.get(componentId)
      if (state) {
        state.isActive = false
        console.warn(`组件 ${componentId} 因32776错误被标记为不活跃`)
      }
    }

    // 触发错误恢复
    this.attemptErrorRecovery(component, data)
  }

  /**
   * 尝试错误恢复
   * @param {Object} component - 组件实例
   * @param {Object} data - 原始数据
   */
  attemptErrorRecovery(component, data) {
    // 延迟重试
    setTimeout(() => {
      if (this.validateComponent(component)) {
        console.log('尝试错误恢复，重新更新数据')
        this.safeUpdate(component, data).catch(() => {
          console.warn('错误恢复失败')
        })
      }
    }, 100)
  }

  /**
   * 获取组件ID
   * @param {Object} component - 组件实例
   * @returns {string}
   */
  getComponentId(component) {
    if (component._uid !== undefined) {
      return `vue_${component._uid}`
    }
    if (component.__wxExparserNodeId__) {
      return `wx_${component.__wxExparserNodeId__}`
    }
    return `component_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }
}

// 创建全局实例
const textUpdateSafe = new TextUpdateSafeWrapper()

// 导出便捷方法
export const safeUpdate = (component, data, callback) => {
  return textUpdateSafe.safeUpdate(component, data, callback)
}

export const registerComponent = (component) => {
  return textUpdateSafe.registerComponent(component)
}

export const deferredUpdate = (component, data, delay) => {
  return textUpdateSafe.deferredUpdate(component, data, delay)
}

export const batchUpdate = (component, updates) => {
  return textUpdateSafe.batchUpdate(component, updates)
}

export default textUpdateSafe